const child_process = require('child_process');
const Watchpack = require('watchpack');
const { PORT } = require('../dist/src/config');

const WATCH_DIRS = ['./dist'];
let worker;

function debounce(fn, time) {
  let lastTime = 0;

  return function (...args) {
    if (Date.now() - lastTime > time) {
      fn(...args);
      lastTime = Date.now();
    }
  };
}

async function run() {
  if (process.platform === 'linux') {
    const killCmd = `lsof -i:${PORT} | grep 'node' | awk '{print "kill -9 "$2}' | sh`;
    console.log(killCmd);
    child_process.execSync(killCmd);
  } else if (worker) {
    worker.kill();
  }

  const args = ['./dist/src/app.js'];

  if (process.env.NODE_ENV === 'debug') {
    args.unshift('--inspect');
  }

  worker = child_process.spawn('node', args, {
    stdio: 'inherit',
    encoding: 'utf-8',
  });

  // worker.on('exit', () => {
  //   console.log('prev server exit');
  // });
}

function createHandler() {
  return debounce(() => {
    console.log('restarting...');
    run();
  }, 1000);
}

const wp = new Watchpack({
  poll: 1000, // 2s轮询间隔
});

wp.watch({
  directories: WATCH_DIRS,
});

wp.on('change', createHandler());
wp.on('remove', createHandler());

run();
